$m(function(args) {
	var that = this;
	var $this = that.element;
	var id = args.id;
	var workSpaceId=args.workSpaceId;
	var $themeViewContainer=$('.theme-container');
    var $themeContainer=$("#tempo-theme-detail-view-layout");	
	var $themeName = $themeContainer.find(".theme-info .tempo-strap-header-title");
	var $themeCreateUserName = $themeContainer.find(".theme-info .theme-info-create-name");
	var $themeCreateDate = $themeContainer.find(".theme-info .theme-info-create-date");
	var $themesceneNum=$themeContainer.find(".theme-info .scene-all-Num");
	var	$themepublishNum=$themeContainer.find(".theme-info .publish-number");
	var $updateNameBtn = $('#tempo-header-updatename-btn');
	var $tableName = $('#tempo-header-themName');
	var $themeDesc = $themeContainer.find(".theme-info #theme-description");
	var $editBtn = $themeContainer.find('.edit-btn');
	var $shareIcon = $themeContainer.find('#tempo-theme-share');
	var $shareBtn = $themeContainer.find('.share-btn');
	var $shareNum=$themeContainer.find('.tempo-theme-share-num');
	var $publishBtn = $themeContainer.find('.publish-btn');
	var $sceneBoard = $themeContainer.find('#theme-blackboard');
	var workSpaceType = $themeViewContainer.attr("workspacetype");
	
	var init = function(){
		initEvent();
		loadPublishNum();
		initLayout();
		toolbar();
		loadTheme(id, renderTheme);
		bindUpdateNameButton();
		addThemeToobarSelectClass($editBtn);
		renderPublishScence();
		initPublish();
		permissionUser();
		initEventBus();
	};
	
	var initEventBus = function(){
		
	    // 授权之后页面授权人数刷新
		Eventbus.bind("permission.theme",permissionUser,this);
		// 发布、取消发布后通知已发布场景数量刷新
		Eventbus.bind("publishNum.theme",loadPublishNum,this);
		Eventbus.bind("publishList.theme",renderPublishScence,this);
    };
	var initEvent=function(){
        $(".theme-more-info").off('click').on('click',function(){
			themeDetail(id);
		});
	};
	var initPublish=function(){
		if(workSpaceType == "self"){
			$("#tempo-theme-publish").hide();
		}
		$("#tempo-theme-publish").mouseover(function(){
			$("#tempo-publish-list").css("left",($(this).offset().left-227)+"px").show();
		});
		$("#tempo-publish-list").mouseover(function(){
			$("#tempo-publish-list").show();
	     });
		$("#tempo-theme-publish,#tempo-publish-list").mouseout(function(){
			$("#tempo-publish-list").hide();
	    });
	};

	/**
	 * 加载应用信息
	 */
	var initLayout = function() {
		$themeContainer.layout({
			north: {
				size: 80,
				resizable : false,
				spacing_open : 0,
				closable : false
			}
		});
	};
	
	var toolbar = function() {
		$editBtn.button({
			click:function(e){
				if(id) {
				    Eventbus.trigger("editTheme.theme",{id:id});
				}
			}
		});
		$publishBtn.button({
			click:function(e){
				if(id) {
					publishTheme(id);
				}
			}
		});
		$shareBtn.button({
			click:function(e){
				if(id) {
					shareTheme();
				}
			}
		});
		$shareIcon.bind("click",shareTheme);
	};
	/**
	 * 发布 resouceId 为应用ID
	 */
	var publishTheme = function(resouceId) {
		var dialog = $("<div/>").appendTo($('body'));
		var url = contextPath + '/api/bi/resource/analyse/view/publish?subjectId='+resouceId;
		$m.loadPage(url,dialog,"tempo-bi-publish-theme-dialog",{"resouceId":resouceId,"dialog":dialog});
		dialog.dialog({
			title:TempoUtils.locale("bidesign.theme_publish"),
			width:900,
			height:520,
			modal:true,
			resizable:false,
			close:function(){
				dialog.dialog("destroy").remove();
			}
		});
	};
    // 授权人数
	var permissionUser=function(){
		var data={resourceId:id,
				workSpaceId:workSpaceId};
		if(workSpaceType == "self"){
			data={resourceId:id};
		}
		$.ajax({
			url:contextPath+"/api/resource/permission/list-users",
			data:data,
			async:false,
			type:'post', 
			success:function(result){
				$shareNum.text(result.data.length);
			}
		});
		
	};
	/**
	 * 获取当前选中的场景id及类型
	 */
	var getCurSceneId = function(themeId){
		var sceneId = null;
		if (themeId != $sceneBoard.attr("_subjectId")){
			return sceneId;
		}
		if (!$sceneBoard[0].contentDocument){
			return sceneId;
		}
		var selectTab = $($sceneBoard[0].contentDocument).find(".tempo-story-tab-curSelect");
		if (selectTab.length == 0){
			return sceneId;
		}
		var sceneId = selectTab.attr("linkid");
		return sceneId;
	};
	/**
	 * 授权应用给其他人，包含取消授权和新增授权 resouceId 为应用ID
	 */
	var shareTheme = function() {
		var buttons=[{
			text:TempoUtils.locale("bidesign.workspace_comfirm"),
			click:function(){
				editPriSave(dialog,id);
				dialog.dialog("close");
			}
		},{
			text:TempoUtils.locale("bidesign.workspace_cancel"),
			click:function(){
				dialog.dialog("close");
			}
		}];
		var type=$themeViewContainer.attr("workspacetype");
		if($themeViewContainer.attr("workspacetype")=='self'){
			buttons=[{
				text:TempoUtils.locale("bidesign.workspace_comfirm"),
				click:function(){
					dialog.dialog("close");
				}
			}];
		}
		var dialog = $('<div>').appendTo($('body'));
		dialog.dialog({
			title:TempoUtils.locale("bidesign.has_shared"),
			width:750,
			height:500,
			modal:true,
			resizable:false,
			open: function(){
				var url = contextPath + '/api/resource/permission/view/index?subjectId=' + id+"&&workSpaceId="+workSpaceId;
				$m.loadHtml(url,dialog,'theme-priv',{subjectId:id,workSpaceId:workSpaceId,workSpaceType:$themeViewContainer.attr("workspacetype")});
			},
			close:function(){
				dialog.dialog("destroy").remove();
			},
			buttons:buttons 
		});
	};
	
	/**
	 * 编辑时获取权限配置数据
	 */
	var editPriSave = function(dialog,resouceId){
		var grid = dialog.find("#tempo-resouce-permission-grid");
		var data = grid.datagrid('getRowData');
		var newPrivi = [],deletePrivi=[];
		if(data && data.length > 0){
			for (var i = 0; i < data.length; i++) {
				var $switchbutton = $('div[id='+data[i].HASPRIVI.substr(data[i].HASPRIVI.indexOf("id=")+4,32)+']');
				// 如果value=manager ,管理权限 跳过
				if($switchbutton.attr('value')=='manager'){
					continue;
				}
				// 如果value=1,有权限，如果选择了关闭，去除权限
				if($switchbutton.attr('value')=='1'&&!$switchbutton.switchbutton('option').open){
					deletePrivi.push(data[i].CODE);
				}
				// 如果value=0,无权限，如果选中了开启，新增
				if($switchbutton.attr('value')=='0'&&$switchbutton.switchbutton('option').open){
					newPrivi.push(data[i].CODE);
				}
			}
		}
		if(deletePrivi.length>0){
			$.ajax({
				url: contextPath+"/api/resource/permission/revoke-by-user-resource",
				data:{
					users : deletePrivi.join(','),
					resourceId : resouceId
				},
				async:false,
				type:'post', 
				success:function(result){
				}
			});
		}
		if(newPrivi.length>0){
			$.ajax({
				url: contextPath+"/api/resource/permission/grant",
				method: 'POST',
				async:false,
				data: {
					resourceId : resouceId,
					users : newPrivi.join(',')
				},
				success: function(data) {
				}
			});
		}
	};
   // 已发布的资源列表
	var renderPublishScence=function(){
		appAjax("/api/bi/resource/scene/list-published", {themeId: id,}, function(data){
			var $publishList=$("#tempo-publish-list").find("ul");
			$publishList.empty();
			if(data.length==0){
			    var li = $("<li/>").appendTo($publishList);
			    $("<span/>",{
					text:"已发布资源可以在此跳转",
				}).appendTo(li).css("cursor","default");
			}
			for(var i=0;i<data.length;i++){
			    var li = $("<li/>",{
			    	id:data[i].ID,
			    	name:data[i].NAME,
			    	class:"tempo-punlish-link"
			    }).appendTo($publishList);
			    $("<span/>",{
					class:"tempo-scene-icon tempo-api-icon-tree-16 tempo-api-icon-tree-16-position-8",
				}).appendTo(li);
				$("<span/>",{
					class:"tempo-punlish-item ",
					title:data[i].NAME,
					text:_subString(data[i].NAME,10)
				}).appendTo(li);
				$("<span/>",{
					class:"ui-icon tempo-ui-icon tempo-ui-icon-uparrows-undertint tempo-punlish-link-icon",
				}).appendTo(li);
			}
			
			$(".tempo-punlish-link").click(function(){
				var id=$(this).attr("id");
				var name=$(this).attr("name");
			    Eventbus.trigger("tabsClick.theme",{
			    	id:id,
			    	name:name
			    });
			});
			
		});
	};
	
	 var _subString = function(str,length){
	    	if(!str){
	    		return str;
	    	}
	    	var  chRegex=/[^\x00-\xff]/g;
	    	var newLength = 0;
	    	var newStr ="";
	    	var strLength = str.replace(chRegex,"**").length;
	    	if(strLength<length){
	    		return str;
	    	}
	    	for (var i = 0; i < strLength; i++) {
				var singleChar = str.charAt(i);
				if(singleChar.match(chRegex)!=null){
					newLength+=2;
				}else{
					newLength++;
				}
				if(newLength>length){
					break;
				}
				newStr+=singleChar;
			}
	    	return newStr+="...";
	    };
	
	var loadTheme = function(id, callback){
		var that = this;
		var process = $("<div/>").tempoprogressbar();
		$.ajax({
			url: contextPath + '/api/bi/resource/analyse/get-detail',
			method: 'POST',
			data: {
				id: id,
				workSpaceId:workSpaceId
			}, 
			success: function(result) {
				var dataInfo = result.data; 
				updateThemeTip("name", dataInfo.themeName);
				updateThemeTip("createName", dataInfo.userName);
				var timeDiff=dataInfo.timeDiff,
				day=timeDiff.day,
				hour=timeDiff.hour,
				min=timeDiff.min;
				var createTime= DateUtils.formatDate(dataInfo.createTime, 'yyyy-MM-dd');
				   if(day>0&&day<3){
					   createTime=day+TempoUtils.locale("bidesign.days_ago");
				   }
				   if(day==0&&hour!=0){
					   createTime=hour+TempoUtils.locale("bidesign.hours_ago");
				   }
				   if(day==0&&hour==0&&min!=0){
					   createTime=min+TempoUtils.locale("bidesign.minutes_ago");
				   }
				   if(day==0&&hour==0&&min==0){
					   createTime=1+TempoUtils.locale("bidesign.minutes_ago");
				   }
				updateThemeTip("createTime", TempoUtils.locale("bidesign.create_time")+createTime);
				callback.call(that, dataInfo);
			}
		}).done(function(){
			process.tempoprogressbar("destroy");
		});
	};
	// 已发布、应用场景数
	var loadPublishNum=function(){
		var that = this;
		var process = $("<div/>").tempoprogressbar();
		$.ajax({
			url: contextPath + '/api/bi/resource/analyse/list-scene-number',
			method: 'POST',
			data: {
				id: id,
			}, 
			success: function(result) {
				var dataInfo = result.data;
				updateThemeTip("sceneAllNum", dataInfo.count);	
				updateThemeTip("publishNum", dataInfo.publishNum);
			}
		}).done(function(){
			process.tempoprogressbar("destroy");
		});
	};
	
	// 头部标题重命名
    var	bindUpdateNameButton=function(){
		$updateNameBtn.unbind('click').bind('click',function(e){
			$updateNameBtn.hide();
			var currentName = $tableName.text();
			$tableName.empty();
			var targetInput = $("<input id='test' value='"+currentName+"'/>").appendTo($tableName);
			targetInput.validatebox({
				tip:TempoUtils.locale("resource.name_valid_tip"),
				required:true,
				maxLength:60,
				autofill:false,
				change : function(){
					var val = targetInput.val();
					var valiresult = renameThemeUtils.specialCharValidNotBracket(val);
		 			if(!valiresult){
		 				targetInput.validatebox("response",false,TempoUtils.locale("bi.base_rename"));
		 			}
				}
			});
			var description=$themeDesc.attr("title");
			targetInput.on("blur",function(e){
				e.stopPropagation();
				if($(this).hasClass('validator-invalid')){
					return;
				}
				var newValue = $(this).val();
				$.ajax({
					url:contextPath + '/api/bi/resource/analyse/update' ,
					method: 'POST',
					data: {
						id:id,
						name:newValue,
						workSpaceId:workSpaceId,
						description:description
					}, 
					success: function(result) {
						if(result.success){
							if (!$.getters("success", result)){
								$("<div/>").alert({
									width:alertDialogWidth,
									height:alertDialogHeight,
									msg:$.getters("message", result)||TempoUtils.locale("bidesign.edit_theme_fail")
								});
								return;
							}
							Eventbus.trigger("updateTopName.theme", {
								type:'theme_private',
								id:id,
								name:newValue
							});
							updateThemeTip("name", newValue);
							$updateNameBtn.show();
						}else{
							$("<div/>").alert({
								msg:result.message
							});
						}
					}
				});
			}).on("keydown", function(event){
				if(event.keyCode == 13){
					$(this).trigger('blur');
				}	
			}).focus();
		});
	};
	 var themeDetail = function(id){
			var dialog = $("<div/>", {
				'class' : 'tempo-theme-operate'
			});
			dialog.append("<div style='text-align:center;width:100%;height:100%;'><div class='detailInfo'><div class='detailInfo-basicInfo'><div class='rs-right-top-l tempo-strap-header-icon tempo-api-icon-48 tempo-api-icon-48-position-2  '></div></div></div></>");
			var tab = $('<div class="bi-theme-detailinfo-tab"><div class="shareInfo"><span>'+TempoUtils.locale("bidesign.theme_share_info")+'</span></div><div class="historyInfo"><span>'+TempoUtils.locale("bidesign.theme_history_info")+'</span></div></div>').appendTo(dialog.find(".detailInfo"));
			var content = $('<div class="infoContent" id="bi-theme-infoContent"></div>').appendTo(dialog.find(".detailInfo"));
			$("<table id='bi-sharedinfo-grid'></table>").appendTo(content);
			dialog.dialog({
				modal : true,
				width : 680,
				height : 480,
				resizable : false, 
				title : TempoUtils.locale("bidesign.app_detail"),
				buttons : [ {
					text : TempoUtils.locale("bidesign.close"),
					click : function() {
						dialog.dialog("destroy").remove();
					}
				} ],
				close : function() {
					dialog.dialog("destroy").remove();
				},
				open: function() {
					// 初始化基本信息
					$.ajax({
						url: contextPath + '/api/bi/resource/analyse/get-detail',
						method: 'POST',
						data: {
							id: id,
							workSpaceId:workSpaceId
						}, 
						success: function(result) {
							var dataInfo = result.data;
							dialog.find('.basicinfo').remove();
							if(dataInfo.description==null||dataInfo.description==""){
								dataInfo.description = TempoUtils.locale("bi.data_base_none");
							}
							$('<div class="basicinfo"><div class="theme-light-color" id="theme-creator">'+TempoUtils.locale("bidesign.create_user")+ dataInfo.userName+'</div>'+
							    '<div class="theme-info-div" id="theme-desc" title="'+dataInfo.description+'">'+TempoUtils.locale("bidesign.theme_desc") + dataInfo.description+'</div>' +
								'<div class="theme-info-div"><span class="theme-basic-item">'+TempoUtils.locale("bidesign.scene_and_report_num")+'</span><span class="theme-deep-color" id="flow-num">'+dataInfo.scenceNum+'</span>'+
								'<span style="margin: 0px 10px;color:#d7dde5">|</span><span class="theme-light-color">'+TempoUtils.locale("bidesign.create_time")+'</span><span class="theme-deep-color" id="createTime">'+DateUtils.formatDate(dataInfo.createTime, 'yyyy-MM-dd hh:mm:ss')  +'</span>'+
								'</div></div>').appendTo($('.detailInfo-basicInfo'));
							
						}
					});
					// 初始化-分享信息、历史信息
					$.ajax({
						url: contextPath + '/api/bi/resource/analyse/list-shared-info', 
						method: 'POST',
						data: {
							id: id,
						}, 
						success: function(result) {
						  if(result.success==true){
							var data=result.data;
							initShareGrid(data);
							
							$(".shareInfo").addClass("bi-theme-info-selecttab").removeClass("bi-theme-info-unselecttab");
							$(".historyInfo").addClass("bi-theme-info-unselecttab").removeClass("bi-theme-info-selecttab");
							
							// 页签事件
							$(".shareInfo").off('click').on('click', function(e) {
								$("#gbox_bi-historyinfo-grid").hide();
								$("#gbox_bi-sharedinfo-grid").show();
								if(!$(this).hasClass('bi-theme-info-selecttab')){
									$(this).addClass("bi-theme-info-selecttab").removeClass("bi-theme-info-unselecttab");
									$(".historyInfo").addClass("bi-theme-info-unselecttab").removeClass("bi-theme-info-selecttab");
								}
							});
							
							
							$(".historyInfo").off('click').on('click', function(e) {
								$("#gbox_bi-sharedinfo-grid").hide();
								$(this).addClass("bi-theme-info-selecttab").removeClass("bi-theme-info-unselecttab");
								$(".shareInfo").addClass("bi-theme-info-unselecttab").removeClass("bi-theme-info-selecttab");
								
								if($("#gbox_bi-historyinfo-grid").length>0){
									$("#gbox_bi-historyinfo-grid").show();
								}else{
									$.ajax({
										url: contextPath + '/api/bi/resource/analyse/history', 
										method: 'POST',
										data: {
											id: id,
										}, 
										success: function(data) {
											$("<table id='bi-historyinfo-grid'></table>").appendTo(content);
											initHistoryGrid(data.data);
										}
									});
								}
							});
						}
					}
					});
					
				}
			}); 
		};
	    
	    var initShareGrid = function(data){
			var colsModel = [{
				name : 'index',
				index : 'index',
				hidden : true
			},{
				name : 'userName',
				index : 'userName',
				align : 'center',
				width : '80px',
				sortable : false
			},{
				name : 'name',
				index : 'name',
				align : 'center',
				width : '80px',
				sortable : false
			},{
				name : 'deptName',
				index : 'deptName',
				align : 'center',
				width : '80px',
				sortable : false
			},{
				name : 'role',
				index : 'role',
				align : 'center',
				width : '200px',
				sortable : false
			}];

			var shareInfoGrid = $('#bi-sharedinfo-grid').datagrid({
				datatype : "local",
				data : data,
				height :120,
				width : 620,
				rownumbers : false,
				hidegrid : false,
				resizable:false,
				striped : true,
				viewrecords : true,
				loadui:'disable',
				multiselect:false,
				pagination:false,
				colNames : ['index', 
				            TempoUtils.locale("bidesign.info_name"),
				            TempoUtils.locale("bidesign.info_pname"),
				            TempoUtils.locale("bidesign.info_dept"),
				            TempoUtils.locale("bidesign.info_role")],
				colModel : colsModel 
			});
		};
		
		
		var initHistoryGrid = function(data){
			var colsModel = [{
				name : 'operation',
				index : 'operation',
				align : 'center',
				width : '80px',
				sortable : false,
				formatter: function(cellvalue){
					return TempoUtils.locale("bidesign."+cellvalue);
				}
			},{
				name : 'operatorcode',
				index : 'operatorcode',
				align : 'center',
				width : '80px',
				sortable : false
			},{
				name : 'operator',
				index : 'operator',
				align : 'center',
				width : '80px',
				sortable : false
			},{
				name : 'deptname',
				index : 'deptname',
				align : 'center',
				resizable:false,
				sortable : false
			},{
				name : 'operatetime',
				index : 'operatetime',
				align : 'center',
				width : '180px',
				sortable : false,
				formatter: function(cellvalue){
					return DateUtils.formatDateTime(new Date(cellvalue), 'yyyy-MM-dd HH:mm:ss');
				}
				
			}];

			var historyInfoGrid = $('#bi-historyinfo-grid').datagrid({
				datatype : "local",
				data : data,
				height :120,
				width : 620,
				rownumbers : false,
				hidegrid : false,
				resizable:false,
				striped : true,
				viewrecords : true,
				loadui:'disable',
				multiselect:false,
				pagination:false,
				colNames : [TempoUtils.locale("bidesign.info_opt"), 
				            TempoUtils.locale("bidesign.info_name"),
				            TempoUtils.locale("bidesign.info_pname"),
				            TempoUtils.locale("bidesign.info_dept1"),
				            TempoUtils.locale("bidesign.info_time")],
				colModel : colsModel 
			});
		};
	
	/**
	 * 修改主题提示信息 type:name名称,desc描述
	 */
	var updateThemeTip = function(type, value){
		if (type == "name"){
			$themeName.text(value).attr("title",value);
		} else if (type == "createName"){
			$themeCreateUserName.text(value).attr("title",value);
		} else if (type == "createTime"){
			$themeCreateDate.text(value).attr("title",value);
		}else if(type == "sceneAllNum"){
			$themesceneNum.text("/"+value).attr("title",value);
		}else if(type == "publishNum"){
			$themepublishNum.text(value).attr("title",value);
		}
	};
	
	var addThemeToobarSelectClass = function(ele) {
		ele.removeClass("ui-button");
		ele.removeClass("tempo-button");
		ele.addClass("theme-strap-header-toolbar-select");
	};
	var appAjax = function(url, param, callback, type, isProcess){
		var that = this;
		var process;
		if (isProcess) {
			process = $("<div/>").tempoprogressbar();
		}
		$.ajax({
			url: contextPath + url,
			data: param,
			type: type || 'post',
			complete: function(XMLHttpRequest, textStatus){
				process ? process.tempoprogressbar("destroy") : "";
			},
			success: function(resultData){
				if (resultData.success) {
					callback.call(that, resultData.data);
				} else {
					$("<div/>").alert({
						width: 500,
						height: 197,
						msg: resultData.message
					});
				}
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				$("<div/>").alert({
					width: 500,
					height: 197,
					msg: "Error!"
				});
			}
		});
	};
	var renameThemeUtils = {
			specialCharValidNotBracket :function(text){
				var regexValid = /^[^~!@#\s\$%\^&\*\+\[\]\|\}\{\\;':,\/<>\?`]+$/;
				if(!regexValid.test(text)){
					return false;
				}
				return true;
			}
	};

	// 设置发布按钮状态，个人空间不能发布应用
	 var setPublishBtnStatus = function(){ 
		 var workspacetype = $themeViewContainer.attr('workspacetype');
		 if(workspacetype != "self"){
			 $publishBtn.show(); 
		 } else {
			 $publishBtn.hide();
		 } 
	 };
	var renderTheme = function(theme){
		if (!theme) {
			return
		};
		setPublishBtnStatus();
		var parent = $sceneBoard.parent();
		$sceneBoard.remove();
		$sceneBoard = $("<iframe class='blackboard' frameborder='0'></iframe>").appendTo(parent);
	    $sceneBoard.attr('_subjectId', id);
		$sceneBoard.attr('src', contextPath + '/api/bi/resource/analyse/view/preview?subjectId=' + id);
	};
	init();
	
});